#include "task\user.h"
#include "rtthread.h"
#include "App\userApp.h"
#include "lcd_BSP.h"
#include "App\beep.h"

uint8_t Bootload_Flag = 0;

#define Get_KEY1() HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin)
#define Get_KEY2() HAL_GPIO_ReadPin(KEY2_GPIO_Port, KEY2_Pin)
void JumpToBootloader(void);

void key_thread_entry(void *parameter)
{
    // PWM_HAL_Init();
    // play_dji_powerup_tone();
    for (;;) {
        rt_thread_mdelay(50);
    }
}

void lcd_thread_entry(void *parameter)
{
    HAL_TIM_Base_Start(&htim8);
    HAL_TIMEx_PWMN_Start(&htim8, TIM_CHANNEL_4);
    // __HAL_TIM_SetCompare(&htim8, TIM_CHANNEL_4, 90);

    LCD_Init();
    LCD_Fill(0, 0, SCREEN_W, SCREEN_H, BLACK);
    LCD_ShowString(24, 54, "Uart uinit", BLACK, RED, 32);
    for (int i = 0; i < 20; i++) {
        __HAL_TIM_SetCompare(&htim8, TIM_CHANNEL_4, 5 * i);
        rt_thread_mdelay(50);
    }
    rt_thread_mdelay(1000);
    for (;;) {
        rt_thread_mdelay(200);
        HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
    }
}

void JumpToBootloader(void)
{
    uint32_t i = 0;
    void (*SysMemBootJump)(void);        /* 声明一个函数指针 */
    __IO uint32_t BootAddr = 0x1FFF0000; /* F407系统BootLoader地址 */
    // LCD_Fill(0, 0, LCD_W, LCD_H, BLACK);
    // LCD_ShowString(20, 32, "Firmware Update", BLUE, BLACK, 16);
    rt_kprintf("boot\n");

    /* 关闭全局中断 */
    __set_PRIMASK(1);
    /* 关闭滴答定时器，复位到默认值 */
    SysTick->CTRL = 0;
    SysTick->LOAD = 0;
    SysTick->VAL  = 0;
    /* 设置所有时钟到默认状态，使用HSI时钟*/
    // RCC_DeInit();
    /* 关闭所有中断，清除所有中断挂起标志 */
    for (i = 0; i < 8; i++) {
        NVIC->ICER[i] = 0xFFFFFFFF;
        NVIC->ICPR[i] = 0xFFFFFFFF;
    }
    /* 使能全局中断 */
    __set_PRIMASK(0);
    /* 跳转到系统BootLoader，首地址是MSP，地址+4是复位中断服务程序地址 */
    SysMemBootJump = (void (*)(void))(*((uint32_t *)(BootAddr + 4)));
    /* 设置主堆栈指针 */
    __set_MSP(*(uint32_t *)BootAddr);
    __set_CONTROL(0);
    SysMemBootJump(); /* 跳转到BootLoader */
}